﻿using System;
using System.Data;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using Business;

namespace NetFlow
{
    public partial class UploadFiles : System.Web.UI.Page
    {
        private static string uploadFolder = "~/UploadedFiles/"; // 服务器存储文件夹

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadUploadedFiles();
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                string fileExtension = Path.GetExtension(FileUpload1.FileName).ToLower();
                string[] allowedExtensions = { ".txt", ".xlsx", ".csv" };

                if (Array.Exists(allowedExtensions, ext => ext == fileExtension))
                {
                    try
                    {
                        string directoryPath = Server.MapPath(uploadFolder);
                        if (!Directory.Exists(directoryPath))
                        {
                            Directory.CreateDirectory(directoryPath);
                        }

                        string fileName = Path.GetFileName(FileUpload1.FileName);
                        string savePath = Path.Combine(directoryPath, fileName);

                        FileUpload1.SaveAs(savePath);

                        Label1.Text = "文件上传成功！";
                        Label1.ForeColor = System.Drawing.Color.Green;

                        LoadUploadedFiles(); // 重新加载文件列表
                    }
                    catch (Exception ex)
                    {
                        Label1.Text = "文件上传失败：" + ex.Message;
                        Label1.ForeColor = System.Drawing.Color.Red;
                    }
                }
                else
                {
                    Label1.Text = "只允许上传 .txt, .xlsx, .csv 文件！";
                    Label1.ForeColor = System.Drawing.Color.Red;
                }
            }
            else
            {
                Label1.Text = "请选择一个文件进行上传！";
                Label1.ForeColor = System.Drawing.Color.Red;
            }
        }

        private void LoadUploadedFiles()
        {
            string directoryPath = Server.MapPath(uploadFolder);
            DataTable dt = new DataTable();
            dt.Columns.Add("FileName");
            dt.Columns.Add("FilePath");

            if (Directory.Exists(directoryPath))
            {
                string[] files = Directory.GetFiles(directoryPath);
                foreach (string file in files)
                {
                    DataRow row = dt.NewRow();
                    row["FileName"] = Path.GetFileName(file);
                    row["FilePath"] = file;
                    dt.Rows.Add(row);
                }
            }

            GridView1.DataSource = dt;
            GridView1.DataBind();
        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string filePath = e.CommandArgument.ToString();

            switch (e.CommandName)
            {
                case "Analyze":
                    Response.Redirect("Overview.aspx?file=" + Server.UrlEncode(filePath));
                    break;
                case "Delete":
                    try
                    {
                        DeleteFile(filePath);
                    }
                    catch
                    {
                        Response.Write("文件删除成功");
                    }
                    break;
            }
        }

        private void ConvertToCSV(string filePath)
        {
            try
            {
                string newFilePath = Path.ChangeExtension(filePath, ".csv");
                File.Copy(filePath, newFilePath, true);
                Label1.Text = "文件已成功转换为 CSV: " + Path.GetFileName(newFilePath);
                Label1.ForeColor = System.Drawing.Color.Green;

                LoadUploadedFiles();
            }
            catch (Exception ex)
            {
                Label1.Text = "转换为 CSV 失败：" + ex.Message;
                Label1.ForeColor = System.Drawing.Color.Red;
            }
        }

        private void ConvertToTXT(string filePath)
        {
            try
            {
                string newFilePath = Path.ChangeExtension(filePath, ".txt");
                File.Copy(filePath, newFilePath, true);
                Label1.Text = "文件已成功转换为 TXT: " + Path.GetFileName(newFilePath);
                Label1.ForeColor = System.Drawing.Color.Green;

                LoadUploadedFiles();
            }
            catch (Exception ex)
            {
                Label1.Text = "转换为 TXT 失败：" + ex.Message;
                Label1.ForeColor = System.Drawing.Color.Red;
            }
        }

        private void ConvertToXLSX(string filePath)
        {
            try
            {
                string newFilePath = Path.ChangeExtension(filePath, ".xlsx");
                File.Copy(filePath, newFilePath, true);
                Label1.Text = "文件已成功转换为 XLSX: " + Path.GetFileName(newFilePath);
                Label1.ForeColor = System.Drawing.Color.Green;

                LoadUploadedFiles();
            }
            catch (Exception ex)
            {
                Label1.Text = "转换为 XLSX 失败：" + ex.Message;
                Label1.ForeColor = System.Drawing.Color.Red;
            }
        }

        private void DeleteFile(string filePath)
        {
            try
            {
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                    Label1.Text = "文件删除成功！";
                    Label1.ForeColor = System.Drawing.Color.Green;

                    LoadUploadedFiles();
                }
                else
                {
                    Label1.Text = "文件不存在，可能已被删除！";
                    Label1.ForeColor = System.Drawing.Color.Red;
                }

                LoadUploadedFiles(); // 重新加载文件列表
            }
            catch (Exception ex)
            {
                Label1.Text = "删除文件失败：" + ex.Message;
                Label1.ForeColor = System.Drawing.Color.Red;
            }
        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            // 这里不需要执行任何代码，只是防止错误
        }

        protected void GridView1_RowDeleting1(object sender, GridViewDeleteEventArgs e)
        {
            // 这里不需要执行任何代码，只是防止错误
        }
    }
}
